import random

from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from verifications import constants
# from you23_bit.libs.yuntongxun.sms import CCP
import logging

logger = logging.getLogger('django')


# GET /sms_code/(?P<mobile>1[3-9]\d{9})


class SMSCodeView(APIView):
    def get(self, request, mobile):
        """短信验证码获取"""

        # 判断60s内服务端是否给客户发送过短信 目的是避免频繁请求
        # 获取redis链接 创建对像
        redis_conn = get_redis_connection('verify_codes')
        send_flag = redis_conn.get("send_flag_%s" % mobile)
        if send_flag:
            return Response({'message': '发送短信过于频繁'}, status=status.HTTP_400_BAD_REQUEST)

        # 1、随机生成6为数字的短信验证码
        # sms_code = '%06d' % random.randint(0, 999999)
        # logger.info("短信验证码是： %s" % sms_code)

        sms_code = '888888'

        # 2、在redis中存储生成的随机验证码
        # 创建管道对象  使用管道可以向redis管道中添加多个命令
        pl = redis_conn.pipeline()
        # 向管道中添加命令
        pl.setex('sms_%s' % mobile, constants.SMS_CODES_REDIS_EXPIRES, sms_code)
        # 保存短信验证码发送标记
        pl.setex('send_flag_%s' % mobile, constants.SEND_SMS_INTERVAL, 1)
        # 一次性执行管道命令
        pl.execute()

        # 3、使用云通讯给手机号发送验证码
        expires = constants.SMS_CODES_REDIS_EXPIRES // 60

        # 发送任务消息
        from celery_tasks.sms.tasks import send_sms_code
        send_sms_code.delay(mobile, sms_code, expires)

        # 4、返回应答，短信发送成功
        return Response({'message': 'OK'})
